#include "main.h"

void TM1638_Init(void)
{
	uint8_t i;
	GPIO_Init(TM1638_PORT, TM1638_CLK|TM1638_STB, GPIO_MODE_OUT_PP_LOW_FAST);
	TM1638_WriteCmd(0x8B);
	TM1638_WriteCmd(0x40);
	GPIO_WriteLow(TM1638_PORT, TM1638_STB);
	for(i=0;i<16;i++)
		TM1638_WriteByte(0x00);
	GPIO_WriteHigh(TM1638_PORT, TM1638_STB);
}

void TM1638_WriteByte(uint8_t data)
{
	uint8_t i,tmp;
	tmp = data;
	// Set DIO as output signal
	GPIO_Init(TM1638_PORT, TM1638_DIO, GPIO_MODE_OUT_PP_LOW_FAST);
	for(i=0;i<8;i++)
	{
		GPIO_WriteLow(TM1638_PORT, TM1638_CLK);
		if (tmp&0x01)
			GPIO_WriteHigh(TM1638_PORT, TM1638_DIO);
		else
			GPIO_WriteLow(TM1638_PORT, TM1638_DIO);
		GPIO_WriteHigh(TM1638_PORT, TM1638_CLK);
	}
}

uint8_t TM1638_ReadByte(void)
{
	uint8_t i, tmp;
	// Set DIO as input signal
	GPIO_Init(TM1638_PORT, TM1638_DIO, GPIO_MODE_IN_PU_NO_IT);
	for(i=0;i<8;i++)
	{
		tmp>>=1;
		GPIO_WriteLow(TM1638_PORT, TM1638_CLK);
		if (GPIO_ReadInputPin(TM1638_PORT, TM1638_DIO))
			tmp |= 0x80;
		GPIO_WriteHigh(TM1638_PORT, TM1638_CLK);
	}
	return tmp;
}

void TM1638_WriteCmd(uint8_t cmd)
{
	GPIO_WriteLow(TM1638_PORT, TM1638_STB);
	TM1638_WriteByte(cmd);
	GPIO_WriteHigh(TM1638_PORT, TM1638_STB);
}

uint8_t TM1638_ReadKey(void)
{
	uint8_t c[4], i, key_value=0;

	GPIO_WriteLow(TM1638_PORT, TM1638_STB);
	TM1638_WriteByte(0x42);
	for(i=0;i<4;i++)
		c[i] = TM1638_ReadByte();
	GPIO_WriteHigh(TM1638_PORT, TM1638_STB);

	for(i=0;i<4;i++)
		key_value|=c[i]<<i;
	for(i=0;i<8;i++)
		if((0x01<<i)==key_value)
			break;
	return i;
}

void TM1638_WriteReg(uint8_t addr, uint8_t data)
{
	TM1638_WriteCmd(0x44);
	GPIO_WriteLow(TM1638_PORT, TM1638_STB);
	TM1638_WriteByte(0xC0|addr);
	TM1638_WriteByte(data);
	GPIO_WriteHigh(TM1638_PORT, TM1638_STB);
}

void TM1638_LED_Ctrl(uint8_t num, uint8_t status)
{
	if (status)
		TM1638_WriteReg(2*num+1, 1);
	else
		TM1638_WriteReg(2*num+1, 1);
}

